package com.dd.utils

import android.graphics.Color
import android.text.Html
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextPaint
import android.text.TextUtils
import android.text.style.ClickableSpan
import android.text.style.URLSpan
import android.view.View


/**
 * Html 组装类
 */
object HtmlUtil {
    /**
     * fromHtml
     *
     * @param content
     * @return
     */
    fun fromHtml(content: String): Spanned {
        return Html.fromHtml(content, Html.FROM_HTML_MODE_LEGACY)
    }

    fun getClickableHtml(html: String, onClick: HtmlOnClick): CharSequence {
        val spannedHtml: Spanned = Html.fromHtml(html, Html.FROM_HTML_MODE_COMPACT)
        val clickableBuilder = SpannableStringBuilder(spannedHtml)
        val urls = clickableBuilder.getSpans(
            0, spannedHtml.length,
            URLSpan::class.java
        )
        if (urls.isEmpty()) {
            return spannedHtml
        }
        //获取所有的URL
        for (span in urls) {
            setLinkClickable(clickableBuilder, span, onClick)
        }
        return clickableBuilder
    }

    //必须设置setMovementMethod(LinkMovementMethod.getInstance());ClickableSpan才会生效
    private fun setLinkClickable(
        clickableHtmlBuilder: SpannableStringBuilder,
        urlSpan: URLSpan,
        onClick: HtmlOnClick
    ) {
        val start = clickableHtmlBuilder.getSpanStart(urlSpan)
        val end = clickableHtmlBuilder.getSpanEnd(urlSpan)
        val flags = clickableHtmlBuilder.getSpanFlags(urlSpan)
        val clickableSpan = MyClickableSpan(urlSpan.url, onClick)
        clickableHtmlBuilder.removeSpan(urlSpan)
        clickableHtmlBuilder.setSpan(clickableSpan, start, end, flags)
    }

    internal class MyClickableSpan(
        private val url: String,
        private val onClick: HtmlOnClick,
        private val color: String = "#0BBDBA"
    ) :
        ClickableSpan() {

        override fun updateDrawState(ds: TextPaint) {
            //设置字体颜色
            ds.color = Color.parseColor(color)
            //去掉下划线
            ds.isUnderlineText = true
        }

        override fun onClick(widget: View) {
            if (!TextUtils.isEmpty(url)) {
                onClick.onClick(url)
            }
        }
    }

    interface HtmlOnClick {
        fun onClick(url: String)
    }
}